std::format
, introduced by C++20, enables straightforward string construction out of values of various types.
Before C++20, one popular way to obtain the same result was the conversion of the values with std::to_string
and piecewise string
concatenation.
std::format
is strictly superior. It is more efficient because it constructs the string in-place instead of copying substrings one by
one. It is also often shorter and easier to read because the format pattern is presented in a single piece and not scattered across the concatenation
expression.
This rule reports string concatenation cases that can be replaced by std::format
to improve performance and readability.
Noncompliant code example
std::string greeting(int n) {
return "Hello, player " + std::to_string(n) + "."; // Noncompliant
}
Compliant solution
std::string greeting(int n) {
return std::format("Hello, player {}.", n); // Compliant
}